import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Divider, Switch } from 'antd';
import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { SorterResult } from 'antd/es/table/interface';

import CreateForm from './components/CreateForm';
import MemberModal from './components/MemberModal';
import { TableListItem } from './data';
import { queryRule, updateRule, addRule, removeRule } from './service';
import UploadFile from '../../../components/FileUpload';

/**
 * 添加节点
 * @param fields
 */
const handle = async (fields: TableListItem, id: any) => {
  const isAdd = !id;
  const txt = isAdd ? '添加' : '编辑';
  const hide = message.loading(`正在${txt}`);
  const params = { ...fields };
  Object.assign(params, { enabled: params.enabled ? 1 : 0 });
  if (!isAdd) {
    Object.assign(params, { id });
  }
  try {
    if (isAdd) {
      await addRule(params);
    } else {
      delete params.id;
      await updateRule(id, params);
    }
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error(`${txt}失败请重试！`);
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[], action: any) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    action.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [memberGroupId, setMemberGroupId] = useState('');
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();

  function renderMemberModal() {
    if (!memberGroupId) {
      return '';
    }
    return (
      <MemberModal
        onCancel={() => {
          setMemberGroupId('');
        }}
        onOk={() => {
          setMemberGroupId('');
          // reloadAuthInfo();
        }}
        groupId={memberGroupId}
        visible
      />
    );
  }

  const fileProps = (item: any) =>
    item.initialValue ? { fileName: [{ url: item.initialValue, name: item.initialValue }] } : {};

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      rules: [
        {
          required: true,
          message: '名称为必填项',
        },
      ],
      labelCol: { span: 6 },
      initialValue: stepFormValues.name,
    },
    {
      title: '跳转地址',
      dataIndex: 'link',
      rules: [
        {
          required: false,
          message: '描述为必填项',
        },
      ],
      hideInSearch: true,
      labelCol: { span: 6 },
      initialValue: stepFormValues.link,
      render: (v) => v || '-',
    },
    {
      title: '是否显示',
      dataIndex: 'enabled',
      rules: [],
      hideInSearch: true,
      labelCol: { span: 6 },
      initialValue: stepFormValues.enabled,
      render: (v) => (v === 1 ? '是' : '否'),
      renderFormItem: (item) => {
        const checkProps = item.initialValue ? { defaultChecked: !!item.initialValue } : {};
        return <Switch {...checkProps} />;
      },
    },
    {
      title: '图片',
      dataIndex: 'image_url',
      rules: [
        {
          required: true,
          message: '名称为必填项',
        },
      ],
      hideInSearch: true,
      labelCol: { span: 6 },
      initialValue: stepFormValues.image_url,
      render: (val) =>
        val && <img alt="商品分类图标" src={val} style={{ width: 130, height: 50 }} />,
      renderFormItem: (item) => {
        const uploadProps = fileProps(item);
        return <UploadFile {...uploadProps} />;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, index, action) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              await handleRemove([record], action);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{}}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setStepFormValues({});
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          const ans = {
            ...params,
            page: params?.current,
          };
          delete ans?.current;
          delete ans?._timestamp;
          const { data } = await queryRule(ans);
          data.data = data.list;
          return data;
        }}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm id={stepFormValues.id} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            const success = await handle(value, stepFormValues.id);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      {renderMemberModal()}
    </PageHeaderWrapper>
  );
};

export default TableList;
